/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.coders;

import java.nio.ByteBuffer;

import org.latestbit.smartobjects.exceptions.*;
import org.latestbit.smartobjects.io.ResizableByteBuffer;
import org.latestbit.smartobjects.network.INetworkCommand;

public class HandshakeRequest extends StdNetworkCommand {
	
	public static final byte COMMAND_ID = 0x04;
	
	public HandshakeRequest(ResizableByteBuffer writeBuffer, IDataTypesCoder coder) {
		super ( COMMAND_ID, writeBuffer, coder );
	}
	
	public HandshakeRequest(INetworkCommand command) {
		super(command);
	}
	
	private byte[] handshakeData;

	@Override
	public void beginSerialize() throws SmartBusSystemException {
		super.beginSerialize();
		ResizableByteBuffer writeBuffer = getBuffer();
		coder.encodeUByteArray(this.handshakeData, writeBuffer);
	}
	
	@Override
	public void deserialize() throws SmartBusSystemException {		
		if(this.getCommandId()!=COMMAND_ID) {
			throw new DataTypesCoderException("Invalid command type id detected ("+this.getCommandId()+" instead "+COMMAND_ID+")!");
		}
		ByteBuffer readBuffer = this.buffer.getBuffer();
		this.handshakeData = coder.decodeUByteArray(readBuffer);
	}
	
	public void setHandshakeData(byte[] publicKey) {
		this.handshakeData = publicKey;
	}

	public byte[] getHandshakeData() {
		return handshakeData;
	}

	public HandshakeResponse createResponse(ResizableByteBuffer writeBuffer) {
		HandshakeResponse response = new HandshakeResponse ( writeBuffer, this.getCoder() );
		response.setMessageId(this.getMessageId());
		return response;
	}	
}
